package com.nd.qa.shareplate.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.nd.qa.shareplate.common.PropertiesManager;
import com.nd.qa.shareplate.common.SessionUserInfo;
import com.nd.qa.shareplate.common.SysConstant;
import com.nd.qa.shareplate.service.ApkService;
import com.nd.qa.shareplate.util.JsonUtil;

/**
 * <br>apk文件上传</br>
 * @author huangjian
 * @createDate 2015-09-22 上午 09:12:12
 * @version V1.0
 */
@Controller
@RequestMapping("/file/*")
public class UploadFileController {

	Logger logger = LoggerFactory.getLogger(UploadFileController.class);
	
	@Autowired
	@Qualifier("com.nd.qa.shareplate.service.ApkService")
	private ApkService apkService;
	
	/**
	 * 上传apk文件
	 * @param request
	 * @param response
	 * @param session
	 * @param params
	 * @throws IOException 
	 */
	@SuppressWarnings({"rawtypes"})
	@RequestMapping("/uploadFile")
	public void uploadFile(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params) throws IOException{
		
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		if (sessionUserInfo==null) {
			resultMap.put("code", "-2");
			resultMap.put("message", "您还未登录");
		}
		// 解析器解析request的上下文
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 先判断request中是否包涵multipart类型的数据，
		if (multipartResolver.isMultipart(request)) {;
			// 再将request中的数据转化成multipart类型的数据
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			Iterator iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				MultipartFile file = multiRequest.getFile((String) iter.next());
				if (file != null) {
					String fileName = file.getOriginalFilename();
					//String savePath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload/"+ fileName);
					String savePath = request.getSession().getServletContext().getRealPath("/resources/file/upload-apk/"+ fileName);
					String savelocalPath = PropertiesManager.localApkPath;
					File serverFile = new File(savePath);
					File localFile = new File(savelocalPath);
					//判断上传文件的保存目录是否存在
					if (!serverFile.exists() && !serverFile.isDirectory()) {
						System.out.println(savePath+"目录不存在，需要创建");
						//创建目录
						serverFile.mkdirs();
					}
					//写文件到服务器上
					try {
						file.transferTo(serverFile);
						//file.transferTo(localFile);
						copyFile(serverFile, localFile, fileName);
						resultMap.put("code", "0");
						resultMap.put("message", "上传文件成功");
						resultMap.put("savePath", "/resources/file/upload-apk/"+ fileName);
						resultMap.put("localApkPath", savelocalPath+fileName);
						resultMap.put("fileName", fileName);
					    response.getWriter().print(JsonUtil.toString(resultMap));
					}catch (IllegalStateException e) {
						e.printStackTrace();
						resultMap.put("code", "-1");
						resultMap.put("message", e.toString());
					    response.getWriter().print(JsonUtil.toString(resultMap));
					}catch (IOException e) {
						e.printStackTrace();
						resultMap.put("code", "-1");
						resultMap.put("message", e.toString());
					    response.getWriter().print(JsonUtil.toString(resultMap));
					}catch (Exception e) {
						e.printStackTrace();
						resultMap.put("code", "-1");
						resultMap.put("message", e.toString());
					    response.getWriter().print(JsonUtil.toString(resultMap));
					}
				}
			}
		}
	}
	
	/**
	 * 上传文件
	 * @param request
	 * @param response
	 * @param session
	 * @param params
	 * @throws IOException 
	 */
	@SuppressWarnings({"rawtypes"})
	@RequestMapping("/uploadDocFile")
	public void uploadDocFile(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params) throws IOException{
		
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		if (sessionUserInfo==null) {
			resultMap.put("code", "-2");
			resultMap.put("message", "您还未登录");
		}
		// 解析器解析request的上下文
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 先判断request中是否包涵multipart类型的数据，
		if (multipartResolver.isMultipart(request)) {;
			// 再将request中的数据转化成multipart类型的数据
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			Iterator iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				MultipartFile file = multiRequest.getFile((String) iter.next());
				if (file != null) {
					String fileName = file.getOriginalFilename();
					//String savePath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload/"+ fileName);
					String savePath = request.getSession().getServletContext().getRealPath("/resources/file/upload-doc/"+ fileName);
					String savelocalPath = PropertiesManager.localDocPath;
					File serverFile = new File(savePath);
					File localFile = new File(savelocalPath);
					//判断上传文件的保存目录是否存在
					if (!serverFile.exists() && !serverFile.isDirectory()) {
						System.out.println(savePath+"目录不存在，需要创建");
						//创建目录
						serverFile.mkdirs();
					}
					//写文件到服务器上
					try {
						file.transferTo(serverFile);
						//file.transferTo(localFile);
						copyFile(serverFile, localFile, fileName);
						resultMap.put("code", "0");
						resultMap.put("message", "上传文件成功");
						resultMap.put("savePath", "/resources/file/upload-doc/"+ fileName);
						resultMap.put("localApkPath", savelocalPath+fileName);
						resultMap.put("fileName", fileName);
					    response.getWriter().print(JsonUtil.toString(resultMap));
					}catch (IllegalStateException e) {
						e.printStackTrace();
						resultMap.put("code", "-1");
						resultMap.put("message", e.toString());
					    response.getWriter().print(JsonUtil.toString(resultMap));
					}catch (IOException e) {
						e.printStackTrace();
						resultMap.put("code", "-1");
						resultMap.put("message", e.toString());
					    response.getWriter().print(JsonUtil.toString(resultMap));
					}catch (Exception e) {
						e.printStackTrace();
						resultMap.put("code", "-1");
						resultMap.put("message", e.toString());
					    response.getWriter().print(JsonUtil.toString(resultMap));
					}
				}
			}
		}
	}
	
	 /** 
     * 复制文件(以超快的速度复制文件) 
     *  
     * @param srcFile 
     *            源文件File 
     * @param destDir 
     *            目标目录File 
     * @param newFileName 
     *            新文件名 
     * @return 实际复制的字节数，如果文件、目录不存在、文件为null或者发生IO异常，返回-1 
     */  
    @SuppressWarnings("resource")
	public static long copyFile(File srcFile, File destDir, String newFileName) {  
        long copySizes = 0;  
        if (!srcFile.exists()) {  
            System.out.println("源文件不存在");  
            copySizes = -1;  
        } else if (!destDir.exists()) {  
            System.out.println("目标目录不存在");  
            copySizes = -1;  
        } else if (newFileName == null) {  
            System.out.println("文件名为null");  
            copySizes = -1;  
        } else {  
            try {  
                FileChannel fcin = new FileInputStream(srcFile).getChannel();  
                FileChannel fcout = new FileOutputStream(new File(destDir,  
                        newFileName)).getChannel();  
                long size = fcin.size();  
                fcin.transferTo(0, fcin.size(), fcout);  
                fcin.close();  
                fcout.close();  
                copySizes = size;  
            } catch (FileNotFoundException e) {  
                e.printStackTrace();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return copySizes;  
    }  
}
